<?php
namespace App\Http\Controllers\Api;

use App\Models\Enum\UserEnum;
use App\Models\Requests\UserRequest;
use Carbon\Carbon;
use App\Models\Requests\BaseRequest;
use Illuminate\Http\Request;
use App\Models\Requests\ProductAttributeKeyRequest;
use App\Models\User;
use App\Models\Resources\UserResource;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;

class UserController extends BaseController
{
    public function index(){
        $users = User::paginate(3);
        return UserResource::collection($users);
    }

    //用户注册
    public function store(UserRequest $request){
        User::create($request->all());
        return '用户注册成功。。。';
    }

    public function store1(ProductAttributeKeyRequest $request)
    {
//        $user = User::create($request->all());

        // 欢迎邮件
//        if ($user->email) {
//            Mail::to($user->email)->send(new Email($user));
//        }

        // 推荐注册逻辑
//        if ($request->get('invite_code')) {
//
//        }

        // 通知运营
//        $user->notify(new NewUser($user));
//        return Auth::login($user);
    }


    //用户登录
    public function login(Request $request)
    {
        $token = Auth::guard('api')->attempt(['name' => $request->name, 'password' => $request->password]);
        if ($token) {

            //如果登陆，先检查原先是否有存token，有的话先失效，然后再存入最新的token
            $users = Auth::guard('api')->user();

            if($users->status==UserEnum::INVALID||$users->status==UserEnum::FREEZE){
                // 不允许用户登录逻辑
                return $this->failed('已冻结', 400);
            }

            if ($users->remember_token) {
                try{
                    Auth::guard('api')->setToken($users->remember_token)->invalidate();
                }catch (TokenExpiredException $e){
                    //因为让一个过期的token再失效，会抛出异常，所以我们捕捉异常，不需要做任何处理
                }
            }
            $IP = Request()->getClientIp();
            $User = User::find($users->id);
////            SaveLastTokenJob::dispatch($User,$token);
            $User->remember_token = $token;
            $User->last_login_ip_at = $IP;
            $User->login_times += 1;
            $User->last_login_at=Carbon::now()->toDateTimeString();

            $User->save();

            return $this->setStatusCode(201)->success(['token' => 'bearer ' . $token]);
        }
        return $this->failed('账号或密码错误', 400);
    }

    //用户退出
    public function logout()
    {
        Auth::guard('api')->logout();
        return $this->success('退出成功...');
    }

    //返回单一用户信息
    public function show(User $user){

        return $this->success(new UserResource($user));
    }

    //返回当前登录用户信息
    public function info(){
        $user = Auth::guard('api')->user();
        return $this->success(new UserResource($user));
    }
}
